﻿using AppDataStruct;
using LogLib;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace EECMISWS
{
    internal partial class WSClient
    {
        private int _queryFrom = 0;
        public int QueryPeopleFrom
        {
            get { return _queryFrom; }
        }

        private QGRKInfo _personInfo = new QGRKInfo();
        public QGRKInfo PersonInfo
        {
            private set { _personInfo = value; }
            get { return _personInfo; }
        }

        /// <summary>
        /// 查询全国人口库(qg_queryPeople没权限了)
        /// </summary>
        private const string funcQueryPeople = "qg_queryPeoplenew";  //qg_queryPeoplenew

        /// <summary>
        /// 查询省常住人口库
        /// </summary>
        private const string funcQueryPeopleReside = "ap_queryPeopleReside";

        /// <summary>
        /// 通过bCity控制省户籍的查询
        /// </summary>
        private const string funcQueryPeopleHousehold = "ap_queryPeopleHousehold";

        /// <summary>
        /// 是否查询省户籍人口
        /// </summary>
        public bool QueryRKK { get; set; }

        /// <summary>
        /// 保存人口库相片信息
        /// </summary>
        /// <param name="strBlob"></param>
        /// <returns></returns>
        private bool SaveBlobData(string strBlob)
        {
            FileStream fStream = null;
            BinaryWriter bWrite = null;
            try
            {
                if (File.Exists(BaseDirectory + "\\temp.jpg"))
                {
                    File.Delete(BaseDirectory + "\\temp.jpg");
                }
                fStream = new FileStream(BaseDirectory + "\\temp.jpg", FileMode.Create, FileAccess.Write);
                bWrite = new BinaryWriter(fStream);
                strBlob.Trim();
                byte[] buffer = Convert.FromBase64String(strBlob);
                bWrite.Write(buffer);
                bWrite.Close();
                fStream.Close();
                Log.WriteAsync($"保存照片成功：{BaseDirectory + "\\temp.jpg"}");
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteException("保存照片异常：" + ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 通过bCity控制省户籍的查询
        /// </summary>
        /// <param name="sfzh"></param>
        /// <param name="strCityCode">citycode传入4至6位调取地市库（如当地有地市库）,citycode不传值或该地无地市库，则会调取省库 </param>
        /// <returns></returns>
        public PeopleQueryResult QueryPeopleHousehold(string sfzh)
        {
            PeopleQueryResult res = new PeopleQueryResult();
            res.DataFrom = QueryFrom.Household;
            JObject jsonResult = new JObject();
            JObject Args = new JObject();
            Args.Add("sfzh", sfzh);
            Args.Add("xm", "");
            Args.Add("csrq", "");
            Args.Add("xb", "");
            Args.Add("citycode", ClientConfig.CityCode.Substring(0, 4));
            string json = Args.ToString();
            WebReturnArgs mReturn = new WebReturnArgs();
            mReturn = CallUnimethod(funcQueryPeopleHousehold, json, true);
            if (!mReturn.CallSuccessed)
            {
                _strMessage = mReturn.ExceptionString;
                res.SetErrorCode(mReturn.ErrorCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            if (!mReturn.Success)
            {
                mReturn.CustomCode = 703;
                _strMessage = string.Format("接口查询错误.\n 详情: 返回代码{0},{1}",
                    mReturn.ErrorCode,
                    mReturn.Message);
                res.SetErrorCode(mReturn.CustomCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            if (string.IsNullOrEmpty(mReturn.DataContent))
            {
                res.Success = true;
                mReturn.CustomCode = 702;
                _strMessage = string.Format("省户籍信息为空.\n 详情: 返回{0},{1}",
                 mReturn.ErrorCode,
                 mReturn.Message);
                res.SetErrorCode(mReturn.CustomCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            Log.WriteAsync("Recev data:" + mReturn.DataContent);
            JObject jObj = JObject.Parse(mReturn.DataContent);
            if (jObj["hjinfos"] == null)
            {
                res.Success = true;
                mReturn.CustomCode = 702;
                _strMessage = "省户籍信息为空!" + mReturn.DataContent;
                res.SetErrorCode(mReturn.CustomCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            string hjrkInfo = jObj["hjinfos"].ToString();
            JArray jArray = JArray.Parse(hjrkInfo);
            if (jArray.Count == 0)
            {
                res.Success = true;
                mReturn.CustomCode = 702;
                _strMessage = "省户籍信息为空!" + mReturn.DataContent;
                res.SetErrorCode(mReturn.CustomCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            res.Success = true;
            string zt = "";//户籍状态，为1或空认为户籍有效                 
            // 注意 户籍库每个地方返回的字段都不一样，只取基本信息，不需要的不取          
            try
            {
                foreach (JObject info in jArray)
                {
                    string zt_temp = "";
                    int xpLen = info["hjbaseinfo"]["xp"].ToString().Length;//相片
                    JToken ztToken = info["hjbaseinfo"]["zt"];
                    if (ztToken != null)
                    {
                        zt_temp = ztToken.ToString();
                    }
                    else
                    {
                        zt_temp = "1";
                    }
                    if (zt_temp.Equals("0"))
                    {
                        zt = zt_temp;
                        continue;
                    }
                    if (!string.IsNullOrEmpty(zt) && zt.Equals("1"))
                    {
                        mReturn.CustomCode = 706;
                        _strMessage = "查询省户籍信息发现异常: 存在多重户籍";
                        res.SetErrorCode(mReturn.CustomCode);
                        res.SetError(_strMessage);
                        Log.WriteAsync(_strMessage);
                        return res;
                    }
                    if (!string.IsNullOrEmpty(zt_temp))
                    {
                        zt = zt_temp;
                    }
                    res.HasData = true;
                    QGRKInfo qgrkInfo = res.PersonInfo;
                    string strBlob = "";
                    qgrkInfo.XB = info["hjbaseinfo"]["xb"].ToString();
                    qgrkInfo.SFZH = info["hjbaseinfo"]["sfzh"].ToString();
                    string csd_code = info["hjbaseinfo"]["csd_code"].ToString();
                    string csd = info["hjbaseinfo"]["csd"].ToString();
                    string str = csd_code + "-" + csd;
                    string hkszd_code = "    户口所在地：" + info["hjbaseinfo"]["hkszd_code"].ToString();
                    string hkszd = "    户口所在地：" + info["hjbaseinfo"]["hkszd"].ToString();
                    //qgrkInfo.CSD = str;
                    qgrkInfo.CSD = csd;
                    qgrkInfo.CSD_CODE = csd_code;
                    qgrkInfo.MZ = info["hjbaseinfo"]["mz"].ToString();
                    qgrkInfo.MZ_CODE = info["hjbaseinfo"]["mz_code"].ToString();
                    qgrkInfo.XM = info["hjbaseinfo"]["xm"].ToString();
                    qgrkInfo.CSRQ = info["hjbaseinfo"]["csrq"].ToString();
                    qgrkInfo.SNSW = "1";
                    strBlob = info["hjbaseinfo"]["xp"].ToString();
                    qgrkInfo.XPDZ = "";
                    if (!string.IsNullOrEmpty(strBlob) && SaveBlobData(strBlob))
                    {
                        res.HasSaveXP = true;
                        qgrkInfo.XPDZ = BaseDirectory + "\\temp.jpg";
                        Log.WriteAsync("照片路径：" + qgrkInfo.XPDZ);
                    }
                    res.PersonInfo = qgrkInfo;
                    Log.WriteAsync("姓名：" + qgrkInfo.XM);
                    Log.WriteAsync("出生日期：" + qgrkInfo.CSRQ);
                    Log.WriteAsync("性别：" + qgrkInfo.XB);
                    Log.WriteAsync("身份证：" + qgrkInfo.SFZH);
                    Log.WriteAsync("民族：" + qgrkInfo.MZ);
                    Log.WriteAsync("户口所在地：" + qgrkInfo.HKSZD);
                }
            }
            catch (ThreadAbortException ex)
            {
                ResetWebServiceClient();
                Log.WriteException(ex.ToString());
                res.SetErrorCode("504");
                res.SetError(ex.Message);
                return res;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                mReturn.CustomCode = 444;
                _strMessage = "解析省户籍信息时程序发生了异常: " + ex.Message;
                Log.WriteAsync(_strMessage);
                return res;
            }
            if (!string.IsNullOrEmpty(zt) && !zt.Equals("1"))
            {
                mReturn.CustomCode = 703;
                _strMessage = string.Format("查询省户籍信息发现异常: 无有效户籍信息.zt : {0}", zt);
                res.SetErrorCode(mReturn.CustomCode);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            _strMessage = "省户籍信息获取成功";
            res.SetError(_strMessage);
            Log.WriteAsync(_strMessage);
            return res;
        }

        /// <summary>
        /// 查询省常住人口信息
        /// </summary>
        /// <param name="sfzh"></param>
        /// <returns></returns>
        public PeopleQueryResult QueryPeopleReside(string sfzh)
        {
            try
            {
                PeopleQueryResult res = new PeopleQueryResult();
                res.DataFrom = QueryFrom.Reside;
                JObject jsonResult = new JObject();
                JObject Args = new JObject();
                Args.Add("sfzh", sfzh);
                Args.Add("xm", "");
                Args.Add("csrq", "");
                Args.Add("xb", "");
                Args.Add("citycode", "");
                string json = Args.ToString();
                WebReturnArgs mReturn = new WebReturnArgs();
                mReturn = CallUnimethod(funcQueryPeopleReside, json, true);
                if (!mReturn.CallSuccessed)
                {
                    res.SetErrorCode(mReturn.ErrorCode);
                    res.SetError(mReturn.ExceptionString);
                    Log.WriteAsync(mReturn.ExceptionString);
                    return res;
                }

                if (!mReturn.Success)
                {
                    mReturn.CustomCode = 703;
                    _strMessage = string.Format("省常住人口查询接口查询错误.\n 详情: 返回代码{0},{1}",
                        mReturn.ErrorCode,
                        mReturn.Message);
                    res.SetErrorCode(mReturn.CustomCode);
                    res.SetError(_strMessage);
                    Log.WriteAsync(_strMessage);
                    return res;
                }
                if (string.IsNullOrEmpty(mReturn.DataContent))
                {
                    res.Success = true;
                    mReturn.CustomCode = 702;
                    _strMessage = string.Format("省常住人口查询省户籍信息为空.\n 详情: 返回{0},{1}",
                     mReturn.ErrorCode,
                     mReturn.Message);
                    res.SetErrorCode(mReturn.CustomCode);
                    res.SetError(_strMessage);
                    Log.WriteAsync(_strMessage);
                    return res;
                }
                Log.WriteAsync("Recv data: " + mReturn.DataContent);
                JObject jObj = JObject.Parse(mReturn.DataContent);
                if (jObj["czrkinfos"] == null)
                {
                    res.Success = true;
                    mReturn.CustomCode = 702;
                    _strMessage = "省常住人口查询省户籍信息为空!";
                    res.SetErrorCode(mReturn.CustomCode);
                    res.SetError(_strMessage);
                    Log.WriteAsync(_strMessage);
                    return res;
                }
                string czrkInfo = jObj["czrkinfos"].ToString();
                JArray jczrkInfo = JArray.Parse(czrkInfo);
                if (jczrkInfo.Count == 0)
                {
                    res.Success = true;
                    mReturn.CustomCode = 702;
                    _strMessage = "省常住人口查询省户籍信息为空!";
                    res.SetErrorCode(mReturn.CustomCode);
                    res.SetError(_strMessage);
                    Log.WriteAsync(_strMessage);
                    return res;
                }
                res.Success = true;
                res.HasData = true;
                QGRKInfo qgrkInfo = res.PersonInfo;
                JObject czrkInfoObj = JObject.Parse(jczrkInfo[0].ToString());
                qgrkInfo.XB = czrkInfoObj["xb"].ToString() == "1" ? "男" : "女";
                qgrkInfo.XB_CODE = czrkInfoObj["xb"].ToString();
                qgrkInfo.SFZH = czrkInfoObj["sfzh"].ToString();
                qgrkInfo.FWCS = czrkInfoObj["fwcs"].ToString();
                qgrkInfo.CYM = czrkInfoObj["cym"].ToString();
                qgrkInfo.CSDXZ = czrkInfoObj["csdxz"].ToString();
                qgrkInfo.JGSSX = czrkInfoObj["jgssx_code"].ToString() + "-" + czrkInfoObj["jgssx"].ToString();
                string str = czrkInfoObj["csd_code"].ToString() + "-" + czrkInfoObj["csd"].ToString();
                str += "    户口所在地：" + czrkInfoObj["hkszd_code"].ToString() + "-" + czrkInfoObj["hkszd"].ToString();
                qgrkInfo.HKSZD = czrkInfoObj["hkszd"].ToString();
                qgrkInfo.HKSZD_CODE = czrkInfoObj["hkszd_code"].ToString();
                //qgrkInfo.CSD = str;
                qgrkInfo.CSD = czrkInfoObj["csd"].ToString();
                qgrkInfo.CSD_CODE = czrkInfoObj["csd_code"].ToString();
                qgrkInfo.BYZK = czrkInfoObj["byzk"].ToString();
                qgrkInfo.HYZK = czrkInfoObj["hyzk"].ToString();
                qgrkInfo.ZZXZ = czrkInfoObj["zzxz"].ToString();
                qgrkInfo.WHCD = czrkInfoObj["whcd"].ToString();
                qgrkInfo.MZ = czrkInfoObj["mz"].ToString();
                qgrkInfo.MZ_CODE = czrkInfoObj["mz_code"].ToString();
                qgrkInfo.XM = czrkInfoObj["xm"].ToString();
                qgrkInfo.CSRQ = czrkInfoObj["csrq"].ToString();
                qgrkInfo.SNSW = "1";
                string strBlob = czrkInfoObj["xp"].ToString();
                qgrkInfo.XPDZ = "";
                if (!string.IsNullOrEmpty(strBlob) && SaveBlobData(strBlob))
                {
                    res.HasSaveXP = true;
                    qgrkInfo.XPDZ = BaseDirectory + "\\temp.jpg";
                    Log.WriteAsync("照片路径：" + qgrkInfo.XPDZ);
                }
                res.PersonInfo = qgrkInfo;
                _strMessage = "省常住人口查询成功";
                Log.WriteAsync("姓名：" + qgrkInfo.XM);
                Log.WriteAsync("出生日期：" + qgrkInfo.CSRQ);
                Log.WriteAsync("性别：" + qgrkInfo.XB);
                Log.WriteAsync("身份证：" + qgrkInfo.SFZH);
                Log.WriteAsync("民族：" + qgrkInfo.MZ);
                Log.WriteAsync("户口所在地：" + qgrkInfo.HKSZD);
                res.SetError(_strMessage);
                Log.WriteAsync(_strMessage);
                return res;
            }
            catch (Exception ex)
            {
                Log.WriteException("QueryPeopleReside异常：" + ex.ToString());
                return null;
            }

        }

        /// <summary>
        /// 查询全国人口库
        /// </summary>
        /// <param name="sfzh"></param>
        /// <returns></returns>
        public PeopleQueryResult QueryPeople_QG(string sfzh)
        {
            PeopleQueryResult res = new PeopleQueryResult();
            res.DataFrom = QueryFrom.QG;
            _strMessage = "";
            JObject jsonResult = new JObject();
            JObject Args = new JObject();
            Args.Add("SFZH", sfzh);
            Args.Add("XM", "");
            Args.Add("CSRQ", "");
            Args.Add("client_ip", ClientConfig.Client_IP);
            Args.Add("client_zsbh", ClientConfig.Client_ZSBH);//不为空即可
            Args.Add("client_dwbh", ClientConfig.TBDWBH);
            Args.Add("client_dwmc", ClientConfig.Client_DWMC);
            Args.Add("client_xm", ClientConfig.Client_XM);
            Args.Add("client_sfzh", ClientConfig.Client_SFZH);

            string json = Args.ToString();
            Log.WriteAsync("全国人口查询 Send：" + "[" + json + "]");
            string result = "";
            int tryCnt = 3;
            int i = 0;
            string exception = "";
            while (i < tryCnt)
            {
                try
                {
                    result = webService.unimethod(_sessionID, funcQueryPeople, json);
                }
                catch (TimeoutException ex)
                {
                    _strMessage = string.Format("eecmiswsPortTypeClient执行操作[{0}]时网络连接超时。\n请联系工作人员或考虑重试! \n详情: {1}",
                        funcQueryPeople,
                        ex.Message);
                    exception = _strMessage;
                    Log.WriteException(ex.ToString());
                    i++;
                    continue;
                }
                catch (ThreadAbortException ex)
                {
                    ResetWebServiceClient();
                    Log.WriteException(ex.ToString());
                    _strMessage = ex.Message;
                    res.SetErrorCode("702");
                    res.SetError(_strMessage);
                    Log.WriteAsync(_strMessage);
                    return res;
                }
                catch (System.ServiceModel.EndpointNotFoundException ex)
                {
                    exception = _strMessage = string.Format("无终结点监听...\n该错误通常是网络中断造成的，请检查网络是否连通.\n异常详情:{0}", ex.Message);
                    Log.WriteException(ex.ToString());
                    i++;
                    continue;
                }
                catch (Exception ex)
                {
                    exception = _strMessage = ex.ToString();
                    Log.WriteException(ex.ToString());
                    i++;
                    continue;
                }
                exception = "";
                break;
            }
            if (!string.IsNullOrEmpty(exception))
            {
                _strMessage = "接口调用发生了异常: " + exception;
                Log.WriteAsync(_strMessage);
                res.SetErrorCode("701");
                res.SetError(_strMessage);
                return res;
            }
            JObject jObj = JObject.Parse(result);
            string errorCode = jObj["state"].ToString();
            string success = jObj["success"].ToString();
            string message = jObj["message"].ToString();
            if (errorCode == "CRJ1002")
            {
                if (!Login())
                {
                    Log.WriteAsync(_strMessage);
                    res.SetErrorCode("701");
                    res.SetError(_strMessage);
                    return res;
                }
                try
                {
                    result = webService.unimethod(_sessionID, funcQueryPeople, json);
                    jObj = JObject.Parse(result);
                    errorCode = jObj["state"].ToString();
                    success = jObj["success"].ToString();
                    message = jObj["message"].ToString();
                }
                catch (TimeoutException ex)
                {
                    _strMessage = string.Format("查询超时.\n请检查网络情况是否正常.\n异常详情:{0}", ex.Message);
                    Log.WriteAsync(_strMessage);
                    Log.WriteException(ex.ToString());
                    res.SetErrorCode(701);
                    res.SetError(_strMessage);
                    return res;
                }
                catch (System.ServiceModel.EndpointNotFoundException ex)
                {
                    _strMessage = string.Format("无终结点监听...\n该错误通常是网络中断造成的，请检查网络是否连通.\n异常详情:{0}", ex.Message);
                    Log.WriteException(ex.ToString());
                    Log.WriteAsync(_strMessage);
                    Log.WriteException(ex.ToString());
                    res.SetErrorCode(701);
                    res.SetError(_strMessage);
                    return res;
                }
                catch (Exception ex)
                {
                    Log.WriteException(ex.ToString());
                    _strMessage = ex.Message;
                    Log.WriteAsync(_strMessage);
                    res.SetErrorCode(701);
                    res.SetError(_strMessage);
                    return res;
                }
            }
            Log.WriteAsync("全国人口查询结果： " + result);
            if (success != "1")
            {
                _strMessage = string.Format("接口查询错误.\n 详情: 返回代码{0},{1}",
                    errorCode,
                    message);
                Log.WriteAsync(_strMessage);
                res.SetErrorCode(703);
                res.SetError(_strMessage);
                return res;
            }
            res.Success = true;
            string strQgrkInfo = jObj["data"]["returnInfos"].ToString();
            JArray jqgrkInfo = JArray.Parse(strQgrkInfo);
            if (string.IsNullOrEmpty(strQgrkInfo) || jqgrkInfo.Count == 0)
            {
                _strMessage = "查询全国人口信息为空";
                Log.WriteAsync(_strMessage);
                res.SetErrorCode(703);
                res.SetError(_strMessage);
                return res;
            }

            QGRKInfo qgrkInfo = res.PersonInfo;

            JObject jInfo = new JObject();
            int index = 0;
            for (; index < jqgrkInfo.Count; index++)
            {
                jInfo = JObject.Parse(jqgrkInfo[index].ToString());
                if ((jInfo["zxsj"] != null && !string.IsNullOrEmpty(jInfo["zxsj"].ToString())) ||
                    (jInfo["rkzt"] != null && (jInfo["rkzt"]["code"].ToString().Contains("迁出") || jInfo["rkzt"]["code"].ToString().Contains("注销")) ||
                    (jInfo["rkglzxlbdm"] != null && (jInfo["rkglzxlbdm"]["code"].ToString().Contains("迁出") || jInfo["rkglzxlbdm"]["code"].ToString().Contains("注销")))))
                {
                    //已经注销的户口，舍弃
                    Log.WriteAsync($"已经注销的户口，舍弃：{jInfo["hkszd"]} - {jInfo["zxsj"]} - {jInfo["rkzt"]["code"]} - {jInfo["rkglzxlbdm"]["code"]}");
                    continue;
                }
                else
                {
                    Log.WriteAsync($"户口有效：{jInfo["hkszd"]} - {jInfo["zxsj"]} - {jInfo["rkzt"]["code"]} - {jInfo["rkglzxlbdm"]["code"]}");
                    break;
                }
            }

            //户口所在地（前两位），中文姓名，出生日期，性别，身份证号，
            //出生地
            string code = "";
            if (jInfo["csd"] != null && jInfo["csd"]["code"] != null)
            {
                qgrkInfo.CSD = GetDataValue(jInfo["csd"]["code"].ToString(), out code);
                qgrkInfo.CSD_CODE = code;
            }
            if (jInfo["hkszd"] != null && jInfo["hkszd"]["code"] != null)
            {
                qgrkInfo.HKSZD = GetDataValue(jInfo["hkszd"]["code"].ToString(), out code);
                qgrkInfo.HKSZD_CODE = code;
            }
            if (jInfo["xb"] != null && jInfo["xb"]["code"] != null)
            {
                qgrkInfo.XB = GetDataValue(jInfo["xb"]["code"].ToString(), out code);
                qgrkInfo.XB_CODE = code;
            }
            if (jInfo["sfzh"] != null)
            {
                qgrkInfo.SFZH = jInfo["sfzh"].ToString();
            }
            if (jInfo["xm"] != null)
            {
                qgrkInfo.XM = jInfo["xm"].ToString();
            }
            if (jInfo["csrq"] != null)
            {
                qgrkInfo.CSRQ = jInfo["csrq"].ToString();
            }
            if (jInfo["mz"] != null && jInfo["mz"]["code"] != null)
            {
                qgrkInfo.MZ = GetDataValue(jInfo["mz"]["code"].ToString(), out code);
                qgrkInfo.MZ_CODE = code;
            }
            if (jInfo["fwcs"] != null)
            {
                qgrkInfo.FWCS = jInfo["fwcs"].ToString();
            }
            if (jInfo["cym"] != null)
            {
                qgrkInfo.CYM = jInfo["cym"].ToString();
            }
            if (jInfo["CSDXZ"] != null)
            {
                qgrkInfo.CSDXZ = jInfo["CSDXZ"].ToString();
            }
            if (jInfo["JGSSX"] != null)
            {
                qgrkInfo.JGSSX = jInfo["JGSSX"].ToString();
            }
            if (jInfo["byqk"] != null && jInfo["byqk"]["code"] != null && jInfo["byqk"]["value"] != null)
            {
                qgrkInfo.BYZK = jInfo["byqk"]["value"].ToString();
                qgrkInfo.BYQK_CODE = jInfo["byqk"]["code"].ToString();
            }
            if (jInfo["zzxz"] != null)
            {
                qgrkInfo.ZZXZ = jInfo["zzxz"].ToString();
            }
            if (jInfo["whcd"] != null && jInfo["whcd"]["code"] != null)
            {
                qgrkInfo.WHCD = GetDataValue(jInfo["whcd"]["code"].ToString(), out code);
                qgrkInfo.WHCD_CODE = code;
            }
            qgrkInfo.SNSW = "0";
            Log.WriteAsync("姓名：" + qgrkInfo.XM);
            Log.WriteAsync("出生日期：" + qgrkInfo.CSRQ);
            Log.WriteAsync("性别：" + qgrkInfo.XB);
            Log.WriteAsync("身份证：" + qgrkInfo.SFZH);
            Log.WriteAsync("民族：" + qgrkInfo.MZ);
            Log.WriteAsync("户口所在地：" + qgrkInfo.HKSZD_CODE);
            _queryFrom = 1;
            //if (string.IsNullOrEmpty(qgrkInfo.MZ)
            //    || string.IsNullOrEmpty(qgrkInfo.HKSZD_CODE)
            //    || string.IsNullOrEmpty(qgrkInfo.XM))
            //{
            //    _strMessage = "户籍信息有缺失，如户口所在地、姓名, 民族等";
            //    res.SetErrorCode(705);
            //    res.SetError(_strMessage);
            //    Log.WriteAsync(_strMessage);
            //    return res;
            //}
            res.HasData = true;
            string strBlob = jInfo["xp"].ToString();

            qgrkInfo.XPDZ = "";
            if (!string.IsNullOrEmpty(strBlob) && SaveBlobData(strBlob))
            {
                res.HasSaveXP = true;
                qgrkInfo.XPDZ = BaseDirectory + "\\temp.jpg";
                Log.WriteAsync("照片路径：" + qgrkInfo.XPDZ);
            }
            else
            {
                Log.WriteAsync("照片路径信息为空:" + jInfo.ToString());
            }
            res.PersonInfo = qgrkInfo;

            _strMessage = "全国人口信息查询成功";
            res.SetError(_strMessage);
            Log.WriteAsync(_strMessage);
            return res;
        }

        public string GetDataValue(string data, out string code)
        {
            code = "";
            try
            {
                string[] datas = data.Split('/');
                if (datas.Length == 2)
                {
                    code = datas[0];
                    return datas[1];
                }
            }
            catch (Exception ex)
            {
                Log.WriteAsync(data + "-解析数据异常:" + ex.ToString());
            }
            return "";
        }
        public bool QueryPeople(string sfzh, out PeopleQueryResult result)
        {
            _personInfo.Reset();
            result = new PeopleQueryResult();
            JObject jsonResult = new JObject();
            try
            {
                if (File.Exists(BaseDirectory + "PeopleInfo.xml"))
                {
                    Log.WriteAsync("先删掉PeopleInfo.xml");
                    File.Delete(BaseDirectory + "PeopleInfo.xml");
                }

                if (File.Exists(BaseDirectory + "temp.jpg"))
                {
                    Log.WriteAsync("先删掉temp.jpg");
                    File.Delete(BaseDirectory + "temp.jpg");
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.Message);
            }

            //if (QueryRKK) //户籍人口
            //{
            //Log.WriteAsync($"准备查询户籍人口：{sfzh}");
            //result = QueryPeopleHousehold(sfzh);
            //if (result != null && result.Success && result.HasData)
            //{
            //    _personInfo = result.PersonInfo;
            //    SaveToXml(result.PersonInfo);
            //    Log.WriteAsync($"查询户籍人口成功：{sfzh}");
            //    return true;
            //}
            //}
            //else
            //{
            Log.WriteAsync($"准备查询省常住人口：{sfzh}");
            result = QueryPeopleReside(sfzh);
            if (result != null && result.Success && result.HasData)
            {
                _personInfo = result.PersonInfo;
                SaveToXml(result.PersonInfo);
                Log.WriteAsync($"查询省常住人口成功：{sfzh}");
                return true;
            }
            //}

            // 如果省户籍查询或者省常住人口库不到信息，从全国库查询  //最新移民局不给这个接口的权限
            Log.WriteAsync($"准备查询全国人口：{sfzh}");
            result = QueryPeople_QG(sfzh);
            if (result != null && result.Success && result.HasData)
            {
                _personInfo = result.PersonInfo;
                SaveToXml(result.PersonInfo);
                Log.WriteAsync($"查询省全国人口成功：{sfzh}");
                return true;
            }
            else
            {
                Log.WriteAsync($"查询省全国人口失败：{sfzh}");
                return false;
            }
        }

        public bool SaveToXml(QGRKInfo qgrkInfo)
        {
            string msg = "";
            bool bRet = Data2Xml.Class2File(qgrkInfo, BaseDirectory + "PeopleInfo.xml", out msg);
            if (!bRet)
            {
                _strMessage = msg;
                Log.WriteAsync(_strMessage);
                return false;
            }
            return true;
        }
    }
}
